<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;
use App\Http\Service\OrderService;
use App\Http\Service\GoodsCommentService;
use App\Http\Service\PointLogService;
use Illuminate\Http\Request;


class OrderController extends BaseController
{

    protected $request;
    protected $user;
    protected $orderService;
    protected $goodsCommentService;
    protected $pointLogService;


    public function __construct(Request $request,
                                OrderService $orderService,
                                GoodsCommentService $goodsCommentService,
                                PointLogService $pointLogService)
    {
        $this->request = $request;
        $this->user = $this->request->get('user');
        $this->orderService = $orderService;
        $this->goodsCommentService = $goodsCommentService;
        $this->pointLogService = $pointLogService;
    }

    public function list()
    {
        $page = $this->request->input('page', 1);

        return toJSON($this->orderService->list($this->user, $page));
    }

    // 确认收货
    public function confirm()
    {
        $this->user = $this->request->get('user');
        $id = $this->request->input('id', 0);


        $order = $this->orderService->findFirstRowByFields(['id' => $id, 'user_id' => $this->user->id]);

        if ($order == null) {
            return toJSON('', \Constant::NEED_SHOW_MESSAGE, '订单不存在');
        }

        if ($order->status != 2) {
            return toJSON('', \Constant::NEED_SHOW_MESSAGE, '非法操作');
        }

        $order->status = 3;
        $order->save();

        return toJSON();
    }


    // 物流查询
    public function logistic()
    {
        $this->user = $this->request->get('user');
        $id = $this->request->input('id', 0);


        $order = $this->orderService->findFirstRowByFields(['id' => $id, 'user_id' => $this->user->id]);

        if ($order == null) {
            return toJSON('', \Constant::NEED_SHOW_MESSAGE, '订单不存在');
        }

        // $company = array(
        //     'STO' => '申通',
        //     'ZTO' => '中通',
        //     'YTO' => '圆通',
        //     'ZJS' => '宅急送',
        //     'EMS' => 'EMS',
        //     'TTKDEX' => '天天',
        //     'SFEXPRESS' => '顺丰',
        // );

        $list = array();

        $url = 'http://api.jisuapi.com/express/query?appkey=0399f6254338a9f3&type=' . $order['logistic_company'] . '&number=' . $order['logistic_number'];
        $result = file_get_contents($url);
        $result = json_decode($result, true);

        if ($result['status'] != 0) {
            return toJSON($list);
        }

        if (!isset($result['result']['list'])) {
            return toJSON( $list);
        }

        foreach ($result['result']['list'] as $v) {
            $list[] = array('time' => $v['time'], 'status' => $v['status']);
        }

        return toJSON($list);

    }

}
